﻿using CefSharp.Wpf;
using NewLife.Log;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using XsClient.CefCommon;
using XsClient.Common;
using XsClient.GUI;

namespace XsClient
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Panuon.UI.Silver.WindowX
    {
        HttpClientX httpClient = null;

        CefSharp.Wpf.ChromiumWebBrowser webBrowser = null;


        public MainWindow()
        {
            InitializeComponent();
            httpClient = HttpClientX.Instance;
            Init();
            try
            {
                var settings = new CefSettings() { };
                webBrowser = new ExtChromiumBrowser() { Address = "http://www.biquge.info/" };
                panelCef.Child = webBrowser;
                //BindBrowser(webBrowser as ExtChromiumBrowser);
                webBrowser.AddressChanged += WebBrowser_AddressChanged;
                //webBrowser.LoadingStateChanged += WebBrowser_LoadingStateChanged;
                HttpClientX.Instance.FrmHost = frmMain;
                
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
                ShowWebMsg(ex.Message);
            }
        }
        private void BindBrowser(ExtChromiumBrowser browser)
        {
            browser.FrameLoadStart += (ss, ee) =>
            {
                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    (ss as ExtChromiumBrowser).Focus();
                }));
            };
        }
        private string webContext = null;
        private void WebBrowser_LoadingStateChanged(object sender, CefSharp.LoadingStateChangedEventArgs e)
        {
            try
            {
                if (e.IsLoading)
                    return;

                webBrowser.Dispatcher.BeginInvoke(new Action(() =>
                {

                    try
                    {
                        var frame = webBrowser.GetBrowser().MainFrame;
                        var context = frame.GetSourceAsync().Result;
                        //XTrace.WriteLine(context?.ToString());
                        webContext = context;
                    }
                    catch (Exception ex)
                    {
                        XTrace.WriteException(ex);
                    }
                }));
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
            }
        }

        private void WebBrowser_AddressChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            try
            {
                string newUrl = e.NewValue.ToString();
                txtCefUrl.Dispatcher.BeginInvoke(new Action(() =>
                {
                    txtCefUrl.Text = newUrl;
                }));
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
            }
        }

        private void Init()
        {
            try
            {
                this.SizeChanged += MainWindow_SizeChanged;
                var helper = AppHelper.Instance;
                XsSysConfig sysConfig = XsSysConfig.Current;
                if (sysConfig != null)
                {
                    if (sysConfig.MainWidth > 100)
                        this.Width = sysConfig.MainWidth;
                    else
                        sysConfig.MainWidth = (int)this.ActualWidth;
                    if (sysConfig.MainHeight > 100)
                        this.Height = sysConfig.MainHeight;
                    else
                        sysConfig.MainHeight = (int)this.ActualHeight;
                    sysConfig.Save();
                }
                else
                    sysConfig = new XsSysConfig();
                if (AppHelper.Instance.BookList == null || AppHelper.Instance.BookList.Books == null || AppHelper.Instance.BookList.Books.Count == 0)
                {
                    AppHelper.Instance.BookList = new BookList() { Books = new List<BookInfo>() };
                    AppHelper.Instance.BookList.Books = Parsers.ResolverFactory.GetResolver().FindBooks("http://www.biquge.info/");
                    helper.BookList.Save();
                }
                ucBooks.ShowBooks(AppHelper.Instance.BookList.Books);
                if (ContextFilter.Current.Filters == null)
                    ContextFilter.Current.Filters = new List<FilterRegex>();
                txtRegex.ItemsSource = ContextFilter.Current.Filters;

                
            }
            catch (Exception ex)
            {
                ShowWebMsg(ex.Message);
            }
        }

        private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            try
            {
                XsSysConfig sysConfig = XsSysConfig.Current;
                if (sysConfig == null)
                {
                    sysConfig = new XsSysConfig();
                }
                sysConfig.MainWidth = (int)this.ActualWidth;
                sysConfig.MainHeight = (int)this.ActualHeight;
                sysConfig.Save();

                sysConfig.Save();
            }
            catch (Exception)
            {

            }
        }

        private void BtnSeach_Click(object sender, RoutedEventArgs e)
        {
            string url = txtUrl.Text.Trim();
            string encoding = cmbEncoding.SelectedItem.ToString();
            ShowWebMsg("", true);
            Task.Factory.StartNew(() =>
            {
                try
                {
                    string bgqtemp = "window.location=";
                    string result = httpClient.GetHtml(url, encoding);
                    //if (result.Contains(bgqtemp))
                    //{
                    //    string tempKey = result.Substring(result.IndexOf(bgqtemp) + bgqtemp.Length + 2, 14);
                    //    result = httpClient.GetHtml(url + tempKey.TrimStart('/'), encoding);
                    //}
                    ShowWebMsg(result);
                }
                catch (Exception ex)
                {
                    ShowWebMsg(ex.Message);
                    HttpClientX.Instance = null;
                    httpClient = HttpClientX.Instance;
                }
            });
        }
        private void ShowWebMsg(string msg, bool reset = false)
        {
            if (txtWebMsg != null)
            {
                txtWebMsg.Dispatcher.Invoke(() =>
                {
                    if (reset)
                        txtWebMsg.Text = "";
                    else
                        txtWebMsg.AppendText(msg + "\r\n");
                });
            }
        }

        private void BtnRegex_Click(object sender, RoutedEventArgs e)
        {
            string str = txtWebMsg.Text.Trim();
            string regexStr = "";
            try
            {
                var filter = (txtRegex.SelectedItem as FilterRegex);
                if (filter == null)
                    return;
                regexStr = filter.RegexStr;
                txtResultMsg.Text = "";
                Regex r = new Regex(regexStr);
                var collection = r.Matches(str);
                if (collection != null && collection.Count > 0)
                {
                    for (int i = 0; i < collection.Count; i++)
                    {
                        var item = collection[i];
                        txtResultMsg.AppendText(item.Value + "\r\n");
                    }
                }
            }
            catch (Exception ex)
            {
                txtResultMsg.Text = ex.Message;
            }
        }

        private void BtnRegexContext_Click(object sender, RoutedEventArgs e)
        {

            string htmlStr = txtWebMsg.Text.Trim();

            try
            {
                txtResultMsg.Text = "";
                string contextRegex = "<div id=\"content\">";
                int startIndex = htmlStr.IndexOf(contextRegex);
                if (startIndex > 0)
                {
                    int endIndex = htmlStr.IndexOf("</div>", startIndex + 24);
                    txtResultMsg.Text = htmlStr.Substring(startIndex + 24, endIndex - startIndex - 60).Replace("<br/>", "\r\n").Replace("&nbsp;", " ");
                }
            }
            catch (Exception ex)
            {
                txtResultMsg.Text = ex.Message;
            }
        }

        private void BtnRegexSet_Click(object sender, RoutedEventArgs e)
        {
            GUI.WinSetRegex winSetRegex = new GUI.WinSetRegex() { WindowStartupLocation = WindowStartupLocation.CenterScreen };
            winSetRegex.ShowDialog();
            txtRegex.ItemsSource = null;
            txtRegex.ItemsSource = ContextFilter.Current.Filters;
        }

        private void btnCefQuery_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string url = txtCefUrl.Text.Trim();
                //webBrowser.GetBrowser().
                webBrowser.Load(url);
            }
            catch (Exception ex)
            {
                ShowWebMsg(ex.Message);
            }
        }

        private void BtnCefPrePage_Click(object sender, RoutedEventArgs e)
        {
            
        }

        private void BtnSeach2_Click(object sender, RoutedEventArgs e)
        {
            string url = txtUrl.Text.Trim();
            string encoding = cmbEncoding.SelectedItem.ToString();
            ShowWebMsg("", true);
            Task.Factory.StartNew(() =>
            {
                try
                {
                    //string bgqtemp = "window.location=";
                    string result = httpClient.GetHtml(url,"UTF8");
                    //if (result.Contains(bgqtemp))
                    //{
                    //    string tempKey = result.Substring(result.IndexOf(bgqtemp) + bgqtemp.Length + 2, 14);
                    //    result = httpClient.GetHtml(url + tempKey.TrimStart('/'), encoding);
                    //}
                    ShowWebMsg(result);
                }
                catch (Exception ex)
                {
                    ShowWebMsg(ex.Message);
                    HttpClientX.Instance = null;
                    httpClient = HttpClientX.Instance;
                }
            });
        }

        private void btnHttpClientBrower_Click(object sender, RoutedEventArgs e)
        {
            if (frmMain.Width < 100)
            {
                frmMain.Width = this.Width - 200;
                frmMain.Height = this.Height - 100;
            }
            else
            {
                frmMain.Width =  20;
                frmMain.Height = 20;
            }
        }

        private void btnSetting_Click(object sender, RoutedEventArgs e)
        {
            WindowSetting win = new WindowSetting() { Owner=this };
            win.ShowDialog();
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            WinSearchBook win = new WinSearchBook() { Owner = this };
            win.ShowDialog();
            ucBooks.ShowBooks(AppHelper.Instance.BookList.Books);
        }
    }
}
